<template>
  <div class="question-poll">
    <p class="question-poll-question">{{ pollQuestion }}</p>
    <div v-if="currentStep === 'type'" class="question-input">
      <!-- 题目类型 -->
      <type-select v-model="form.type_id" />
    </div>
    <div v-else-if="currentStep === 'style'" class="question-input">
      <!-- 题目类型 -->
      <div class="form-style">
        <mu-radio v-model="form.style" class="form-style-item" :value="0" label="选择题"></mu-radio>
        <mu-radio v-model="form.style" class="form-style-item" :value="1" label="填空题"></mu-radio>
      </div>
    </div>
    <div v-else-if="currentStep === 'text'" class="question-input">
      <!-- 题干 -->
      <mu-text-field v-model="form.text" full-width placeholder="请在这里输入题干" multi-line :rows="1" :rows-max="3"></mu-text-field>
    </div>
    <div v-else-if="currentStep === 'image'" class="question-input">
      <!-- 图片 -->
      <div class="form-has-image">
        <mu-radio v-model="hasImage" class="form-style-item" :value="false" label="无"></mu-radio>
        <mu-radio v-model="hasImage" class="form-style-item" :value="true" label="有"></mu-radio>
      </div>
      <image-input v-if="hasImage" v-model="form.image" />
    </div>
    <div v-else-if="currentStep === 'options'" class="question-input">
      <!-- 选项 -->
      <options-input ref="optionsInput" v-model="form.options" />
    </div>
    <div v-else-if="currentStep === 'answer_text'" class="question-input">
      <!-- 填空题答案 -->
      <mu-text-field v-model="form.answer" full-width placeholder="请在这里输入答案" multi-line :rows="1" :rows-max="3"></mu-text-field>
    </div>
    <div v-else-if="currentStep === 'answer_option'" class="question-input">
      <!-- 选择题答案 -->
      <answer-select v-model="form.answer" :options="form.options" />
    </div>

    <!-- 消息提示区 -->
    <div class="question-alert">
      <ul class="error-list mu-error-color">
        <li v-for="msg in valid.errors" :key="msg" class="error-item">{{ msg }}</li>
      </ul>
      <ul class="warning-list">
        <li v-for="msg in valid.warnings" :key="msg" class="warning-item">{{ msg }}</li>
      </ul>
    </div>

    <!-- 步骤栏 -->
    <div class="question-actions">
      <mu-button v-if="canBack" class="question-actions-button" color="orange" @click="move(-1)">上一步</mu-button>
      <mu-button v-if="canForward" class="question-actions-button" color="success" @click="forward()">下一步</mu-button>
      <template v-if="canSubmit">
        <mu-button v-if="qcConfig.preview" class="question-actions-button" color="success" @click="preview()">预览</mu-button>
        <mu-button v-else class="question-actions-button" :color="submitButtonInfo.color" @click="submit()">{{ submitButtonInfo.text }}</mu-button>
      </template>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapMutations } from 'vuex'
import { Question } from '@/util/validate'
import { convertCreateQuestionStatusToButtonInfo } from '@/util'
import { submitQuestion } from '@/mixins'
import TypeSelect from '@/components/TypeSelect'
import OptionsInput from '@/components/OptionsInput'
import AnswerSelect from '@/components/AnswerSelect'
import ImageInput from '@/components/ImageInput'

export default {
  name: 'QuestionPoll',
  components: {
    TypeSelect,
    AnswerSelect,
    ImageInput,
    OptionsInput
  },
  mixins: [
    submitQuestion
  ],
  props: {
    modified: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      hasImage: true,
      form: {
        type_id: 0,
        style: 0,
        text: '',
        image: null,
        options: [],
        answer: ''
      },
      status: {
        id: 0,
        submitting: false,
        question: false,
        image: false
      },
      currentStep: 'type',
      last: '',
      valid: {
        errors: [],
        warnings: []
      },
      commit: 0
    }
  },
  computed: {
    ...mapGetters({
      qcConfig: 'questionCreateConfig'
    }),
    pollPath() {
      if (this.form.style === 0) {
        return [
          'type',
          'style',
          'text',
          'image',
          'options',
          'answer_option'
        ]
      } else {
        return [
          'type',
          'style',
          'text',
          'image',
          'answer_text'
        ]
      }
    },
    pollQuestion() {
      const map = {
        type: '你想要出一个什么类型题目呢？',
        style: '这道题是选择题还是填空题呢？',
        text: '题干是什么呢？',
        image: '这道题有图片吗？',
        options: '选项分别是哪些呢？',
        answer_text: '答案是什么呢？',
        answer_option: '答案是哪一个呢？'
      }
      return map[this.currentStep] || ('系统错误，请联系管理员（' + this.currentStep + '）')
    },
    currentStepIndex() {
      return parseInt(this.pollPath.indexOf(this.currentStep))
    },
    canBack() {
      return this.currentStepIndex > 0
    },
    canForward() {
      return this.currentStepIndex < (this.pollPath.length - 1)
    },
    canSubmit() {
      return this.currentStepIndex === (this.pollPath.length - 1)
    },
    formJson() {
      return JSON.stringify(this.form)
    },
    lastEqaulsForm() {
      return this.last !== this.formJson
    },
    submitButtonInfo() {
      return convertCreateQuestionStatusToButtonInfo(this.status)
    }
  },
  watch: {
    formJson() {
      this.commit = 0
    },
    lastEqaulsForm(val) {
      this.$emit('update:modified', val)
    }
  },
  created() {
    this.clearForm()
  },
  methods: {
    ...mapMutations({
      setQcConfig: 'SET_QUESTION_CREATE_CONFIG',
      setQcForm: 'SET_QUESTION_CREATE_FORM'
    }),
    // 移动步骤
    move(diff) {
      const steps = this.pollPath
      const index = this.currentStepIndex
      const next = (index + steps.length + parseInt(diff)) % steps.length
      this.currentStep = steps[next]
    },
    // 检查输入是否有效
    checkValid() {
      var result = null
      switch (this.currentStep) {
        case 'type': result = Question.checkType(this.form); break
        case 'style': result = Question.checkStyle(this.form); break
        case 'text': result = Question.checkText(this.form); break
        case 'image': result = Question.checkImage(this.form, this.hasImage); break
        case 'options': result = Question.checkOptions(this.form); break
        case 'answer_option':
        case 'answer_text':
          result = Question.isValid(this.form) // 最后一次直接检查整个题目
          break
      }
      if (result === null) {
        result = { errors: [], warnings: [] }
      }
      const { errors, warnings } = this.valid = result
      if (errors.length > 0) {
        this.$toast.error('题目存在错误，不能提交')
      } else if (warnings.length > 0 && this.commit === 0) {
        this.$toast.warning('题目可能存在问题，仍要继续请再次点击“查看预览”')
      }
      const isValid = (errors.length === 0 && warnings.length === 0) || (errors.length === 0 && this.commit >= 1)
      // 记录尝试一次
      if (isValid) {
        this.commit = 0
      } else {
        this.commit++
      }
      return isValid
    },
    // 更新QcConfig
    updateQcConfig() {
      const config = { ...this.qcConfig }
      switch (this.currentStep) {
        case 'type': config.type_id = this.form.type_id; break
        case 'style': config.style = this.form.style; break
        case 'image': config.has_image = this.hasImage; break
        case 'options': config.option_count = this.form.options.length; break
      }
      this.setQcConfig(config)
    },
    // 刷新QcForm
    updateQcForm() {
      const form = { ...this.form }
      if (form.style === 1) {
        form.options = []
      }
      this.setQcForm(form)
    },
    // 下一步
    forward() {
      this.updateQcConfig()
      if (this.checkValid()) {
        this.move(1)
      }
    },
    // 预览
    preview() {
      this.updateQcConfig()
      if (this.checkValid()) {
        this.last = JSON.stringify(this.form)
        this.updateQcForm()
        this.$nextTick(() => {
          this.$router.push({ name: 'question-create-preview' })
        })
      }
    },
    // 提交题目
    async submit() {
      if (await this.submitQuestion()) {
        this.clearForm()
        this.clearStatus()
      }
    },
    // 清空表单
    clearForm() {
      const n = this.qcConfig.option_count
      this.form.type_id = this.qcConfig.type_id
      this.form.style = this.qcConfig.style
      this.form.options = Array(n).fill('')
      this.form.image = null
      this.form.text = ''
      this.form.answer = ''
      this.hasImage = this.qcConfig.has_image
      this.last = JSON.stringify(this.form)
      this.currentStep = 'type'
    },
    // 清空状态
    clearStatus() {
      this.status = {
        id: 0,
        submitting: false,
        question: false,
        image: false
      }
    }
  }
}
</script>

<style scoped>
.question-poll {
  padding: 12px;
}
.question-poll-question {
  padding: 1em;
  font-size: 2em;
  text-align: center;
}
.question-input {
  margin: 0 auto;
  width: 500px;
}

.form-style {
  display: flex;
  justify-content: space-around;
}
.form-has-image {
  padding: 6px 0;
  display: flex;
  justify-content: space-around;
}

.question-alert {
  margin: 16px auto;
  width: 500px;
}
.question-actions {
  text-align: center;
}
.question-actions-button {
  margin: 6px;
}

.error-list,
.warning-list {
  list-style: none;
  color: #fff;
}
.warning-list {
  background-color: #fb8c00;
}
.error-item,
.warning-item {
  padding: 6px 9px;
}

.is-phone .question-input {
  width: 100%;
}
.is-phone .question-alert {
  width: 100%;
}
</style>
